import {
  memo,
  MouseEventHandler,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import type { FC, PropsWithChildren } from 'react';
import { useNavigate } from 'react-router-dom';
import { AutoComplete, SelectProps, Tag } from 'antd';
import { resSearchHot } from '@/services/search';
import { useLocalHistoryRecordStore } from '@/store/localHistorySearchRecord';
import { useRequest } from 'ahooks';
import QueueAnim from 'rc-queue-anim';
import AppIcon from '@/components/AppIcon';
import HomeInputSearch from '@/pages/Home/components/HomeInputSearch';
import './index.scss';

const HomeSearch: FC<PropsWithChildren<{}>> = () => {
  const { data } = useRequest(resSearchHot);
  const navigate = useNavigate();
  const { addRecord } = useLocalHistoryRecordStore();

  const isUnmount = useRef(false);
  useEffect(() => {
    return () => {
      isUnmount.current = true;
    };
  }, []);

  const onTagClickHandler: MouseEventHandler<HTMLSpanElement> = (event) => {
    addRecord(event.currentTarget.innerText, isUnmount);
    goSearch(event.currentTarget.innerText);
  };

  const goSearch = useCallback((q: string) => {
    navigate(`/search?q=${q}`);
  }, []);

  return (
    <section key={'search'} className={'text-center pt-7'}>
      <HomeInputSearch />
      <QueueAnim
        className={
          'py-2 w-[50%] min-w-[50%] flex flex-wrap m-auto leading-[30px] min-h-[76px]'
        }
      >
        <div key={'hot-search'}>
          <Tag color="blue" icon={<AppIcon icon={'icon-hot-fill'} />}>
            热搜
          </Tag>
        </div>
        {data
          ? data.map((value) => (
              <div key={value.keyword}>
                <Tag
                  color="blue"
                  onClick={onTagClickHandler}
                  className={'cursor-pointer'}
                >
                  {value.keyword}
                </Tag>
              </div>
            ))
          : null}
      </QueueAnim>
    </section>
  );
};

export default memo(HomeSearch);
